<?php
/**
 * 接口控制器
 */
namespace Admin\Controller;

use Think\Controller;
use Think\Log;

class GoodsApiController extends ApiBaseController
{
	public function index(){
		
		$faliure_dataSn = array();
		$faliure_dataSn = array_diff(array('a','b','c'),array('b','d'));//同步失败的商品货号数组
		
		var_dump($faliure_dataSn);
		
		$str ='中';
		echo mb_strlen($str,'utf8');
		echo '<br/>';
		$str ='哈';
		echo mb_strlen($str,'utf8');
		
		exit;
		
		echo "no you can't go on ! ";exit;
	}
	
	/* 获取商品销量数据接口 ?s=/GoodsApi/getGoodsSalers */
	public function getGoodsSalersBackUp(){
        
        //先验证接口是否为合法调用
        $request_token= I('request.token','','trim');
        //得到系统token
        $local_token=C('token'); 
        //如果token不一致，则返回消息。
        if($request_token !=$local_token ){
            $result = array('resultCode'=>0,'resultMsg'=>'token 校验不一致，无权进行操作','dataSn'=>null,'faliure_dataSn'=>null);
            echo json_encode($result);
            exit;
        }
        
        
		$_eighty_days=strtotime("-180 days");
		$_ninty_days=strtotime("-90 days");
		$args = array(
				'model' => M('goods'),
				'field' => "g.goods_sn,
				SUM(IF(oi.`add_time` >= {$_eighty_days} ,og.goods_number,0)) AS eighteen_saler,
				SUM(IF(oi.`add_time` >= {$_ninty_days} ,og.goods_number,0)) AS ninty_saler,
				g.goods_number,(cast(g.goods_number as signed) - cast(g.wait_sendgoods_stock as signed)) as can_sale_goods_number",
				'group' => 'g.goods_id',
				'join' => array(
						_CTN('order_goods').' as og on og.goods_id = g.goods_id ',
						_CTN('order_info').' as oi on oi.order_id = og.order_id ',
				),
				'alias' => 'g',
				'listrows' => 30,
				'count' =>'distinct g.goods_id'
						);
		
		$list_sort = I('list_sort', '', 'trim');
		$list_sort = !empty($list_sort) ? $list_sort : 'g__goods_sn desc';
		
		$args = $this->_searchCommon($args, $list_sort, array('oi.`pay_status`'=>2,'g.is_on_sale'=>1,'g.is_delete'=>0));
		
		
		/*这里需要组装sql start*/
		$order_str='';
		if (strpos($args['order'],'real_can_saler_days')!==false){
			$order_str=' order by '.$args['order'];//记录原始的排序
			$args['order']='g.goods_sn';
		}
		$_args=$args;
		
		//获取sql语句
		$list_sql = $this->getListsSql($args);
		$select_sql = " select goods_sn,Floor(
			case  when (eighteen_saler / 180) = 0 then 0
			when (ninty_saler / 90) = 0 then 0
			when (can_sale_goods_number / (eighteen_saler / 180)) > (can_sale_goods_number / (ninty_saler / 90)) then (can_sale_goods_number / (ninty_saler / 90))
			else (can_sale_goods_number / (eighteen_saler / 180))
			end )
			as real_can_saler_days from ( {$list_sql} ) AS SubQueryAlias {$order_str} ";
		$count_sql = " select count(*) as count from ( {$list_sql} ) AS SubQueryAlias limit 1";
		/*这里需要组装sql end*/
		$_args['count_sql'] = $count_sql;
		$_args['select_sql'] = $select_sql;
		$goodsList=$this->listsFromSql($_args,false,false);
		
		echo json_encode(array('goodsData'=>$goodsList));
		exit;
	}
	
	//获取商品销量
	public function getGoodsSalers(){
        
        //先验证接口是否为合法调用
        $request_token= I('request.token','','trim');
        //得到系统token
        $local_token=C('token'); 
        //如果token不一致，则返回消息。
        if($request_token !=$local_token ){
            $result = array('resultCode'=>0,'resultMsg'=>'token 校验不一致，无权进行操作','dataSn'=>null,'faliure_dataSn'=>null);
            echo json_encode($result);
            exit;
        }
		
		$_eighty_days=strtotime("-180 days");
		$_ninty_days=strtotime("-90 days");
		$args = array(
				'model' => M('goods'),
				'field' => "g.goods_sn,
				SUM(IF(oi.`add_time` >= {$_eighty_days} ,og.goods_number,0)) AS eighteen_saler,
				SUM(IF(oi.`add_time` >= {$_ninty_days} ,og.goods_number,0)) AS ninty_saler",
				'group' => 'g.goods_id',
				'join' => array(
						_CTN('order_goods').' as og on og.goods_id = g.goods_id ',
						_CTN('order_info').' as oi on oi.order_id = og.order_id ',
				),
				'alias' => 'g',
				'listrows' => 30,
				'count' =>'distinct g.goods_id'
						);
		
		$list_sort = I('list_sort', '', 'trim');
		$list_sort = !empty($list_sort) ? $list_sort : 'g__goods_sn desc';
		
		$args = $this->_searchCommon($args, $list_sort, array('oi.`pay_status`'=>2,'g.is_on_sale'=>1,'g.is_delete'=>0));
		
		
		/*这里需要组装sql start*/
		$order_str='';
		if (strpos($args['order'],'real_can_saler_days')!==false){
			$order_str=' order by '.$args['order'];//记录原始的排序
			$args['order']='g.goods_sn';
		}
		$_args=$args;
		
		//获取sql语句
		$list_sql = $this->getListsSql($args);
		$select_sql = " select goods_sn,
					if( (eighteen_saler / 180)>(ninty_saler /90),(eighteen_saler / 180),(eighteen_saler / 180) ) as real_can_saler_days 
					from ( {$list_sql} ) AS SubQueryAlias {$order_str} ";
		$count_sql = " select count(*) as count from ( {$list_sql} ) AS SubQueryAlias limit 1";
		/*这里需要组装sql end*/
		$_args['count_sql'] = $count_sql;
		$_args['select_sql'] = $select_sql;
		$goodsList=$this->listsFromSql($_args,false,false);
		
		echo json_encode(array('goodsData'=>$goodsList));
		exit;
		
	}
	
	
	/* 获取当前商品可售库存接口 */
	public function getGoodsNumberInfo(){
        
        //先验证接口是否为合法调用
        $request_token= I('request.token','','trim');
        //得到系统token
        $local_token=C('token'); 
        //如果token不一致，则返回消息。
        if($request_token !=$local_token ){
            $result = array('resultCode'=>0,'resultMsg'=>'token 校验不一致，无权进行操作','dataSn'=>null,'faliure_dataSn'=>null);
            echo json_encode($result);
            exit;
        }
        
		$args = array(
				'model' => M('goods'),
				'field' => "g.goods_sn,g.goods_number,(cast(g.goods_number as signed) - cast(g.wait_sendgoods_stock as signed)) as can_sale_goods_number",
				'group' => 'g.goods_id',
				'alias' => 'g',
				'listrows' => 30,
// 				'count' =>'distinct g.goods_id'
						);
		
		$list_sort = I('list_sort', '', 'trim');
		$list_sort = !empty($list_sort) ? $list_sort : 'g__goods_sn desc';
		
		$args = $this->_searchCommon($args, $list_sort, array('g.is_delete'=>0));
		
		$goodsList =  $this->lists($args,false,false);
		
		echo json_encode(array('goodsData'=>$goodsList));
		exit;
	}
	
	
	/* 同步修改商品 */
	public function updateGoodsInfo(){
        
        //先验证接口是否为合法调用
        $request_token= I('request.token','','trim');
        //得到系统token
        $local_token=C('token'); 
        //如果token不一致，则返回消息。
        if($request_token !=$local_token ){
            $result = array('resultCode'=>0,'resultMsg'=>'token 校验不一致，无权进行操作','dataSn'=>null,'faliure_dataSn'=>null);
            echo json_encode($result);
            exit;
        }
		
		$goodsData = I('request.goodsData','','trim');
        
		//写入日志
		write_file_aomai_ftp_v2('updateGoodsInfo','goods_update','data1:'.$goodsData);	
        
		if(empty($goodsData) ){
			$result = array('resultCode'=>0,'resultMsg'=>'澳代端未检测到同步的商品数据。','dataSn'=>null);
		}else{
			
			$goods_data_json = stripslashes($goodsData);	//商品货号 ，要修改的库存		
			$goods_data = json_decode($goods_data_json,true);
			$goods_sn_arry = array();//商品货号数组
			$faliure_dataSn = array();//同步失败的商品货号数组
			
			//循环遍历进销存传过来的需要更新的商品对象集合
			foreach ($goods_data as $v){	
                
                $goods_sn = $v['goods_sn'];//商品货号	
                
				//先查询商品是否存在，存在则修改
				$goods_id = M('goods')->where(array('goods_sn'=>$goods_sn))->getField('goods_id');
                //如果存在该商品，则更新
				if(!empty($goods_id) ){					
                    
                    $goods_number = intval($v['goods_number']);//商品库存
                    //如果库存小于0，则库存-0
                    if( $goods_number < 0 ){
                        $goods_number = 0;
                    }
 
                    
                    $update_data['last_update'] = time();
                    $update_data['goods_number'] = $goods_number;
                    
                    //修改库存的日志
                    write_file_aomai_ftp_v2('updateGoodsInfo','goods_update','update_data:'.json_encode($update_data));
                    
                    //修改商品记录
                    M('goods')->where(array('goods_id'=>$goods_id))->save($update_data);

                    //设置goods_item_id下的所有商品的 public_goods_id 为 is_general=1 的那条记录的商品ID
					// if(!empty($v['goods_item_id']) ){
					//      $goods_id= $goods_db->where(array('goods_item_id'=>$v['goods_item_id'],'is_general'=>1))->getField('goods_id');
	    //                  if($goods_id){
	    //                  	$goods_db->where(array('goods_item_id'=>$v['goods_item_id']))->setField('public_goods_id',$goods_id);
	    //                  }
					// }
                    
                    
                    $goods_sn_arry[]=$goods_sn;
				}else{
					$faliure_dataSn[]=$goods_sn;
				}


                
			}
			
			$result = array('resultCode'=>1,'resultMsg'=>count($goods_sn_arry).'个商品数据同步成功!','dataSn'=>$goods_sn_arry);
			
		}

		 //设置多属性主商品记录的库存数量
         // $this->setEnTrySkuGoodsNumber();
		
		echo json_encode($result);		
		exit;
		
	}
	
	 
	//同步新增商品
	public function addGoodsInfo(){
        
        //先验证接口是否为合法调用
        $request_token= I('request.token','','trim');
        //得到系统token
        $local_token=C('token'); 
        
        //如果token不一致，则返回消息。
        if($request_token !=$local_token ){
            $result = array('resultCode'=>0,'resultMsg'=>'token 校验不一致，无权进行操作','dataSn'=>null,'faliure_dataSn'=>null);
            echo json_encode($result);
            exit;
        }
        
        //获取商品信息
		$goodsData = I('request.goodsData','','trim');
		
        //如果获取到的商品信息为空
		if( empty($goodsData) ){
            
			$result = array('resultCode'=>0,'resultMsg'=>'澳买端未检测到同步的商品数据。','dataSn'=>null,'faliure_dataSn'=>null);
            
		}else{
			
			$log_data =null; //记录日志的data
			if( is_array($goodsData) ){
				$goods_data = $goodsData;
				
				$log_data = json_encode($goodsData);
			}else{
				$log_data = $goodsData;
				
				$goods_data_json = stripslashes($goodsData);
					
				$goods_data_json = str_replace('()', '\\', $goods_data_json);
				
				$goods_data = json_decode($goods_data_json,true);
			}
			
            write_file_aomai_ftp_v2('addGoodsInfo','goods_update','data1:'.$log_data);	            
            
            
			$goods_sn_arry = array();//商品货号数组
			$faliure_dataSn = array();//同步失败的商品货号数组
            
            $goods_db = M('goods');//
            //循环遍历进销存传过来的需要更新的商品对象集合
            foreach ($goods_data as $v){

                //因为同步时是根据goods_sn同步的
              	
            	
                $return_arry = $this->commonDealGoods($v, $goods_sn_all, $goods_sn_arry);
                //获取返回的数组
                $goods_sn_arry = $return_arry['goods_sn_arry'];
                $goods_sn_all = $return_arry['goods_sn_all'];

                //设置goods_item_id下的所有商品的 public_goods_id 为 is_general=1 的那条记录的商品ID
				if(!empty($v['goods_item_id']) ){
				     $goods_id= $goods_db->where(array('goods_item_id'=>$v['goods_item_id'],'is_general'=>1))->getField('goods_id');
                     if($goods_id){
                     	$goods_db->where(array('goods_item_id'=>$v['goods_item_id']))->setField('public_goods_id',$goods_id);
                     }
				} 
                
            }
            

            
			$result = array('resultCode'=>1,'resultMsg'=>count($goods_sn_arry).'个商品数据同步成功!','dataSn'=>$goods_sn_arry,'faliure_dataSn'=>$faliure_dataSn);
            
		}

		 //设置多属性主商品记录的库存数量
         $this->setEnTrySkuGoodsNumber();
		
		echo json_encode($result);
		exit;
		
	}
	
	/* 处理goods数据 */
	public function commonDealGoods($v,$goods_sn_all,$goods_sn_arry){
		
		//2016-09-01 update
		$v['is_delete']=0;
		
		$goods_sn = $v['goods_sn'];//商品货号
		
		//条形码
		$v['bar_code'] =empty($v['bar_code'])?"": $v['bar_code'];
		
		//商品名称【进销存里的商品名称为英文名称，所以同步到51M或者澳买的时候，要把接收到的商品名称赋值给 goods_englishname，然后移除 goods_name这个键，以免更新了商品中文名称 】
		$goods_name = $v['goods_name'];//英文名称
		if(!empty($goods_name) ){
			$v['goods_englishname'] = $goods_name;
		}
		
		//邮寄重量
		$mailweight = $v['mailweight'];
		//如果重量字段没有传过来，则不更新重量
		if(empty($mailweight)){
			unset($v['goods_weight']);
		}else{
			$new_goods_weight = $mailweight /1000;
			//如果除以 1000 后，所得的值大于 0.003 则为有效值，否则不更新重量
			if($new_goods_weight>0.003)
			{
				$v['goods_weight'] = $new_goods_weight;
			}else{
				unset($v['goods_weight']);
			}
		
		}
		
		//税率
		$taxrate = $v['tax_rate'];
		$v['taxrate']=$taxrate;
		
		//报关价
		//$custom_clearance_price = $v['custom_clearance_price'];
		
		//货架号
		$shelfnumber = $v['shelf_number'];
		$v['shelfnumber']=$shelfnumber;
		
		//是否代销（分销） 1是 0否
		//$distribution = $v['distribution'];
		
		 
		$goods_sn_all[] = $goods_sn;
		
		//移除和数据库字段不一致的键
		unset($v['tax_rate']);  //税率
		unset($v['shelf_number']);  //货架号
		
		unset($v['goods_name']); //移除 goods_name ,应为不能更新中文名称
		unset($v['goods_desc']);  //不能同步商品描述
		unset($v['goods_desc_mobile']);  //手机版描述内容不能同步
		unset($v['mailweight']); //进销存重量字段不能要
		
		//先查询商品是否存在，不存在则新增
		$goods_id = M('goods')->where(array('goods_sn'=>$goods_sn))->getField('goods_id');
        

        //商品项ID
		$goods_item_id=intval($v['goods_item_id']);

		//如果商品不存在，则添加一条商品记录
		if(empty($goods_id) ){
		
			$v['goods_desc']='';
			$v['goods_desc_mobile']='';
			$v['add_time'] = time();  //添加时间
			$v['is_on_sale'] = 0; //默认不上架
			$v['is_general'] = intval($v['is_general']);//is_general
			$v['goods_item_id'] = intval($v['goods_item_id']);
			$v['is_private'] = intval($v['is_private']);//
			 
			write_file_aomai_ftp_v2('addGoodsInfo_Add','goods_update','add_data:'.json_encode($v));
		
			//插入商品记录
			M('goods')->add($v);
			 
		   //循环attr_goods记录数据
		   $attr_goods = isset($v['attr_goods'])?$v['attr_goods']:array();
		   if( !empty($attr_goods) ){
		   		foreach ($attr_goods as $ag){
		   			$this->commonDealGoods($ag, array(),array());
		   		}
		   }
			 
			//获取goods对应的goods_item数据并添加
			$goods_item = isset($v['goods_item'])?$v['goods_item']:array();
			if( !empty($goods_item) ){
				$goods_item_record = M('goods_item')->where(array('id'=>$goods_item['id']))->find();
				if( empty($goods_item_record) ){
					M('goods_item')->add($goods_item);
				
					write_file_aomai_ftp_v2('addGoodsInfo_Add','goods_update','add_goods_item_data:'.json_encode($goods_item));
				}
			}	
			
			//获取attr_item_imgs 数据并添加
			$attr_extends_items = isset($v['attr_extends_items'])?$v['attr_extends_items']:array();
			if( !empty($attr_extends_items) ){
				foreach ($attr_extends_items as $_item){
					unset($_item['id']);//移除id
					$goods_item_attr_items = M('goods_attribute_extends_items')
							->where(array(
								'cat_id'=>$_item['cat_id'],
								'attribute_group_id'=>$_item['attribute_group_id'],
								'goods_attribute_value_id'=>$_item['goods_attribute_value_id'],
								'goods_item_id'=>$_item['goods_item_id'],	
							))
							->find();
					if( empty($goods_item_attr_items) ){						
						M('goods_attribute_extends_items')->add($_item);
							
						write_file_aomai_ftp_v2('addGoodsInfo_Add','goods_update','add_goods_attribute_extends_items_data:'.json_encode($_item));
					}
				}				
			}
		
			$goods_sn_arry[]=$goods_sn;
		
		}else{
		
			//最后更新时间
			$v['last_update'] = time();
		
			write_file_aomai_ftp_v2('addGoodsInfo_Update','goods_update','update_data:'.json_encode($v));
		
			//更新商品记录
			M('goods')->where(array('goods_id'=>$goods_id))->save($v);
		
			//循环attr_goods记录数据
			$attr_goods = isset($v['attr_goods'])?$v['attr_goods']:array();
			if( !empty($attr_goods) ){
				foreach ($attr_goods as $ag){
					$this->commonDealGoods($ag, array(),array());
				}
			}
			
			//获取goods对应的goods_item数据并修改
			$goods_item = isset($v['goods_item'])?$v['goods_item']:array();
			if( !empty($goods_item) ){
				$goods_item_record = M('goods_item')->where(array('id'=>$goods_item['id']))->find();
				if( !empty($goods_item_record) ){
					$goods_item_id = $goods_item['id'];
					unset($goods_item['id']);
					M('goods_item')->where(array('id'=>$goods_item_id))->save($goods_item);
				
					write_file_aomai_ftp_v2('addGoodsInfo_Add','goods_update','update_goods_item_data:'.json_encode($goods_item));
				}else{
					//没有goods_item数据就添加
					M('goods_item')->add($goods_item);
						
					write_file_aomai_ftp_v2('addGoodsInfo_Add','goods_update','add_goods_item_data:'.json_encode($goods_item));
				}
			}	
			
			//获取attr_item_imgs 数据并添加
			$attr_extends_items = isset($v['attr_extends_items'])?$v['attr_extends_items']:array();
			if( !empty($attr_extends_items) ){
				foreach ($attr_extends_items as $_item)
				{
					unset($_item['id']);//移除id
					$goods_item_attr_items = M('goods_attribute_extends_items')
						->where(array(
							'cat_id'=>$_item['cat_id'],
							'attribute_group_id'=>$_item['attribute_group_id'],
							'goods_attribute_value_id'=>$_item['goods_attribute_value_id'],
							'goods_item_id'=>$_item['goods_item_id'],
						))
						->find();
					if( empty($goods_item_attr_items) ){
						M('goods_attribute_extends_items')->add($_item);
					
						write_file_aomai_ftp_v2('addGoodsInfo_Add','goods_update','add_goods_attribute_extends_items_data:'.json_encode($_item));
					}else{						
						M('goods_attribute_extends_items')
							->where(array(
								'cat_id'=>$_item['cat_id'],
								'attribute_group_id'=>$_item['attribute_group_id'],
								'goods_attribute_value_id'=>$_item['goods_attribute_value_id'],
								'goods_item_id'=>$_item['goods_item_id'],
							))->save($_item);		
						
						write_file_aomai_ftp_v2('addGoodsInfo_Add','goods_update','update_goods_attribute_extends_items_data:'.json_encode($_item));
					}
				}				
			}


		
			$goods_sn_arry[]=$goods_sn;
		
		}


		
		//$goods_sn_all,$goods_sn_arry
		return array('goods_sn_all'=>$goods_sn_all,'goods_sn_arry'=>$goods_sn_arry);
	}
	
	
	
	/**
     * 查询组合$args 参数
     * @param  [type] $args      [description]
     * @param  [type] $list_sort [description]
     * @return [type]            [description]
     */
	public function _searchCommon($args, $list_sort, $where = array())
	{
        
		$param = array();
		//排序
		$param['list_sort'] = $list_sort;
        
		$_sort_arry = explode(' ', trim($list_sort));
        
		$this->assign("{$_sort_arry[0]}", $_sort_arry[1]);//分配排序
		$this->assign('_sort', $_sort_arry[1]);
		$this->assign("th_a", $_sort_arry[0]);
        
		$price = I('price', '', 'trim');
		$goods_name = I('goods_name', '', 'trim');
		$goods_sn = I('goods_sn', '', 'trim');
		$goods_ename = I('goods_ename', '', 'trim');
		$cat_id = I('cat_id',0,'intval');
        
		if ($price) {
			$param['price'] = $price;
			$where['g.shop_price'] = array('like', "%{$price}%");
		}
		if ($goods_name) {
			$param['goods_name'] = $goods_name;
			$where['g.goods_name'] = array('like', "%{$goods_name}%");
		}
		if ($goods_sn) {
			$param['goods_sn'] = $goods_sn;
			$where['g.goods_sn'] = array('like', "%{$goods_sn}%");
		}
		if ($goods_ename) {
			$param['goods_ename'] = $goods_ename;
			$where['g.goods_englishname'] = array('like', "%{$goods_ename}%");
		}
		//类别id
		if(!empty($cat_id)){
			$param['cat_id'] = $cat_id;
			$where['g.cat_id'] = $cat_id;
		}
        
        
        
		//支付时间
		$time_start = I('start_time', '', 'trim');
		$time_end = I('end_time', '', 'trim');
		$str = '1=1 ';
		if ($time_start) {
			$str .= " and oi.pay_time >= " . strtotime($time_start).C('DEFAULT_TIMEZONE_STR').' ';
		}
		if ($time_end) {
			$str .= " and  oi.pay_time <= " . strtotime($time_end).C('DEFAULT_TIMEZONE_STR').' ';
		}
		$param['start_time'] = $time_start;
		$param['end_time'] = $time_end;
		$where['_string'] = $str;
        
		$args['order'] = strpos($list_sort,'__')!==false?str_replace('__','.',$list_sort):$list_sort;
		$args['page_param'] = $param;
		$args['where'] = $where;
        
		return $args;
        
	}

	
	private function write_file($file_name,$content){
        
		$filename =$file_name.'.log';
		$Ts=fopen($filename,"a+");
		fputs($Ts,"\r\n".$content);
		fclose($Ts);
	}

	 //设置多属性主商品记录的库存数量
	public function setEnTrySkuGoodsNumber(){

	   $goodsDB=M('goods');


       //得到多属性商品的主记录
       $goodsList=$goodsDB->field('goods_id,goods_item_id')->where(array('is_delete'=>0,'is_have_attrs'=>1))->select();
       foreach ($goodsList as $key => $value) {
        	$goods_item_id=$value['goods_item_id'];
        	$goods_id=$value['goods_id'];

        	//得到 goods_item_id 下的所有实际库存，可售库存，待发或库存，更新到  goods_id 记录里。
        	$goodsEntity= $goodsDB->field('sum(goods_number) as goods_number,sum(wait_sendgoods_stock) as wait_sendgoods_stock')
        	->where(array('goods_item_id'=>$goods_item_id,'is_can_set_number'=>1,'is_delete'=>0))->find();
            write_file_aomai_ftp_v2('setEnTrySkuGoodsNumber','goods_update','RES1:'. json_encode($goodsEntity));	
            
            $updateGoodsData=array();
        	$updateGoodsData['goods_number']=intval($goodsEntity['goods_number']);
        	$updateGoodsData['wait_sendgoods_stock']=intval($goodsEntity['wait_sendgoods_stock']);
        	// $can_sale_goods_number=intval($goodsEntity['goods_number']) - intval($goodsEntity['wait_sendgoods_stock']);
        	// $can_sale_goods_number=($can_sale_goods_number<=0?0:$can_sale_goods_number);
            // $updateGoodsData['can_sale_goods_number']=$can_sale_goods_number;

            $goodsDB->where(array('goods_id'=>$goods_id))->save($updateGoodsData);
            write_file_aomai_ftp_v2('setEnTrySkuGoodsNumber','goods_update','SQL2:'. $goodsDB->getlastSql());	 
     
        }



	}


	/* 同步商品的价格信息 */
	public function updateGoodsPrices(){


		// local_retail_price   本地零售价
		// local_vip_price      本地会员价
		// exit_member_price    出口会员价
		// exit_vip_price       出口vip价
		// customize_price1     自定义价格1
		// customize_price2     自定义价格2
		// customize_price3     自定义价格3
		// customize_price4     自定义价格4
		// customize_price5     自定义价格5
        
        //先验证接口是否为合法调用
        $request_token= I('request.token','','trim');
        //得到系统token
        $local_token=C('token'); 
        //如果token不一致，则返回消息。
        if($request_token !=$local_token ){
            $result = array('resultCode'=>0,'resultMsg'=>'token 校验不一致，无权进行操作','dataSn'=>null,'faliure_dataSn'=>null);
            echo json_encode($result);
            exit;
        }
		
		$goodsData = I('request.goodsData','','trim');
        
		//写入日志
		write_file_aomai_ftp_v2('updateGoodsPrices','goods_update','data1:'.$goodsData);	
        
		if(empty($goodsData) ){
			$result = array('resultCode'=>0,'resultMsg'=>'澳代端未检测到同步的商品数据。','dataSn'=>null);
		}else{
			
			$goods_data_json = stripslashes($goodsData);	//商品货号 ，要修改的库存		
			$goods_data = json_decode($goods_data_json,true);
			$goods_sn_arry = array();//商品货号数组
			$faliure_dataSn = array();//同步失败的商品货号数组
			
			//循环遍历进销存传过来的需要更新的商品对象集合
			foreach ($goods_data as $v){	
                
                $goods_sn = $v['goods_sn'];//商品货号
				//先查询商品是否存在，存在则修改
				$goods_id = M('goods')->where(array('goods_sn'=>$goods_sn))->getField('goods_id');
                //如果存在该商品，则更新
				if(!empty($goods_id) ){					
                    
                    $local_retail_price = doubleval($v['local_retail_price']);//本地零售价
                    $local_vip_price = doubleval($v['local_vip_price']);//本地会员价
                    $exit_member_price = doubleval($v['exit_member_price']);//出口会员价
                    $exit_vip_price = doubleval($v['exit_vip_price']);//出口vip价
                    $customize_price1 = doubleval($v['customize_price1']);//自定义价格1
                    $customize_price2 = doubleval($v['customize_price2']);//本地零售价2
                    $customize_price3 = doubleval($v['customize_price3']);//本地零售价3
                    $customize_price4 = doubleval($v['customize_price4']);//本地零售价4
                    $customize_price5 = doubleval($v['customize_price5']);//本地零售价5
                   
  
                    $update_data['last_update'] = time();
                    $update_data['local_retail_price'] =$local_retail_price;
                    $update_data['local_vip_price'] =$local_vip_price;
                    $update_data['exit_member_price'] =$exit_member_price;
                    $update_data['exit_vip_price'] =$exit_vip_price;
                    $update_data['customize_price1'] =$customize_price1;
                    $update_data['customize_price2'] =$customize_price2;
                    $update_data['customize_price3'] =$customize_price3;
                    $update_data['customize_price4'] =$customize_price4;
                    $update_data['customize_price5'] =$customize_price5;
                    
                   
                    //修改商品记录
                    M('goods')->where(array('goods_id'=>$goods_id))->save($update_data);
                    $lastSql=M('goods')->getlastSql();
                    //修改库存的日志
                    write_file_aomai_ftp_v2('updateGoodsPrices','goods_update','update_data-SQL:'. $lastSql);
                    
                    $goods_sn_arry[]=$goods_sn;
				}
                //如果商品不存在
				else{
					$faliure_dataSn[]=$goods_sn;
				}
                
			}
			
			$result = array('resultCode'=>1,'resultMsg'=>count($goods_sn_arry).'个商品数据同步成功!','dataSn'=>$goods_sn_arry);
			
		}
		
		echo json_encode($result);		
		exit;
	}
	
}

?>

